package org.chronologger.poppaea.client.widgets;

import static org.chronologger.poppaea.client.widgets.LocationWidget.LOCATION_WIDGET_HEIGHT;

import java.util.HashMap;

import org.chronologger.poppaea.client.Chronology;
import org.chronologger.poppaea.client.domain.ChronologyData;
import org.chronologger.poppaea.client.domain.Location;
import org.chronologger.poppaea.client.i18n.LocationBarConsts;
import org.chronologger.poppaea.client.utils.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;

public class LocationBarWidget extends Composite {

	public static final LocationBarConsts lang = GWT
			.create(LocationBarConsts.class);
	protected final ChronologyData cdata;
	protected final AbsolutePanel locationsPanel = new AbsolutePanel();
	protected final HashMap<Location, LocationWidget> locationWidgets = new HashMap<Location, LocationWidget>();

	public LocationBarWidget(ChronologyData cdata) {
		this.cdata = cdata;
		initWidget(locationsPanel);
		setWidth(Chronology.LOCATION_PANEL_WIDTH + "px");
		locationsPanel.setSize("100%", "100%");
	}

	public void createWidgetsForData() {
		for (Location l : cdata.locations) {
			addLocationWidget(l);
		}
	}

	/**
	 * Adds a new location to both the bar and the locationList
	 * 
	 * @param name
	 */
	public Location addLocation(String name) {
		Location newLocation = cdata.addLocation();
		newLocation.setName(name);
		newLocation.updateOnServer();
		addLocationWidget(newLocation);
		return newLocation;
	}

	private LocationWidget lastWidget = null;

	private void addLocationWidget(Location location) {
		int top = 0;
		if (lastWidget != null) {
			top = locationsPanel.getWidgetTop(lastWidget)
					+ lastWidget.getOffsetHeight()
					+ Chronology.LOCATION_WIDGET_GAP;
			Logger.notice("OffsetHeight: " + lastWidget.getOffsetHeight());
		}
		Logger.notice("Top: " + top);
		LocationWidget newWidget = new LocationWidget(location);
		locationsPanel.add(newWidget, Chronology.LOCATION_WIDGET_GAP, top);
		setHeight((top + LOCATION_WIDGET_HEIGHT) + "px");
		locationWidgets.put(location, newWidget);
		lastWidget = newWidget;
	}

}
